import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

class Util {
  /// 十六进制颜色，
  /// hex, 十六进制值，例如：0xffffff,
  /// alpha, 透明度 [0.0,1.0]
  static Color hexColor(int hex, {double alpha = 1}) {
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    return Color.fromRGBO((hex & 0xFF0000) >> 16, (hex & 0x00FF00) >> 8,
        (hex & 0x0000FF) >> 0, alpha);
  }
}

extension StringExt on String {
  ///图片完成路径
  String get img {
    var _name = this;
    if (!_name.startsWith('asset/images/')) {
      _name = 'asset/images/3.0x/' + _name;
    }
    if (!_name.endsWith('.png')) {
      _name += '.png';
    }
    return _name;
  }

  ///获取本地图片
  Image get uiimg => Image.asset(
        img,
        scale: 3,
      );

  Image uiimgw(
    double w, {
    Color? color,
  }) =>
      Image.asset(
        img,
        width: w,
        scale: 3,
        color: color,
      );

  ///eq完整指令14字节
  String fullCmd() => padRight(28, '0');

  ///同一网段
  bool isSameNet(String ip2) {
    var ip1s = split('.');
    var ip2s = ip2.split('.');
    if (ip1s.length != 4 || ip2s.length != 4) {
      return false;
    }
    var ip1Prefix = ip1s.sublist(0, 2).join();
    var ip2Prefix = ip2s.sublist(0, 2).join();
    return ip1Prefix == ip2Prefix;
  }

  ///转换为日期20230524230549
  DateTime toDateTime() {
    var dt = this;
    if (dt.length < 14) {
      dt = dt.padRight(14, '0');
    }
    int year = int.parse(dt.substring(0, 4));
    int month = int.parse(dt.substring(4, 6));
    int day = int.parse(dt.substring(6, 8));
    int hour = int.parse(dt.substring(8, 10));
    int minute = int.parse(dt.substring(10, 12));
    int second = int.parse(dt.substring(12, 14));
    return DateTime(year, month, day, hour, minute, second);
  }
}

extension IntExt on int {
  ///转为16进制小端模式 1393=>9d06 [width]暂用宽度
  String toHexString({int width = 2}) {
    assert(width >= 2 && (width % 2 == 0));
    String v = toRadixString(16).padLeft(width, '0');
    // List<String> list = [];
    // for (var i = 0; i < v.length; i+=2) {
    //   list.add(v.substring(i, i + 2));
    // }
    // return list.reversed.join();
    return v;
  }

  ///1=>01
  String get h2 => toHexString();

  ///1=>0001
  String get h4 => toHexString(width: 4);

  ///1=>00000001
  String get h8 => toHexString(width: 8);

  ///是否在区域内
  bool isInRange(int start, int end) => this >= start && this <= end;

  ///宽度适配 1186 200
  double get w => this * max(Get.width, Get.height) / 850.0;
}

extension DoubleExt on double {
  //宽度适配
  double get w => toInt().w;
}
